<?php
/**
 * Created by PhpStorm.
 * User: 65736
 * Date: 2019/4/3 0003
 * Time: 14:00
 */

namespace app\common\model\wechat;


use app\common\library\CommonFun;
use app\common\model\article\PublishArticleModel;
use app\common\model\article\PublishWeiboModel;
use app\common\model\coin\CoinRuntimeModel;
use app\common\model\CommonModel;
use app\common\model\rbac\RbacAdminModel;
use app\common\service\swoolejobs\WeChatPushJobs;

class WeChatPushArticleModel extends CommonModel
{
    /**
     * 数据库配置
     *
     * @var string
     */
    protected $connection = 'db_config_wechat';

    /**
     * 表名称
     *
     * @var string
     */
    protected $table = "wechat_push_article";


    /**
     * 初始化方法
     * {@inheritDoc}
     * @see CommonModel::initialize()
     */
    protected function initialize()
    {
        parent::initialize();

    }

    /**
     * 文章类型
     * @var string
     */
    const TypeArticle = 'article';

    /**
     * 微博类型
     * @var string
     */
    const TypeWeiBo = 'weibo';


    /**
     * 添加到需要推送的数据列表 18.11.12 @thinkphp 修改
     * @param int $coin_id
     * @param int $exchange_id 交易所ID
     * @param int $article_id
     * @param int $type
     * @param string $push_wechat_time
     * @return boolean
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addPushList($coin_id, $exchange_id, $article_id, $type, $push_wechat_time = '')
    {
        $is_delay = 0;
        if ($push_wechat_time) {
            $is_delay = 1;
        } else {
            $push_wechat_time = date('Y-m-d H:i:s');
        }


        $insert = array(
            "coin_id" => $coin_id,
            "exchange_id" => $exchange_id,
            "article_id" => $article_id,
            'is_delay' => $is_delay,
            "type" => $type
        );


        $push_data = $this->where($insert)->find();

        if ($push_data) {
            $this->update_data($push_data['id'], array("push_time" => $push_wechat_time));
            return true;
        }

        $insert['push_time'] = $push_wechat_time;

        $add_res = $this->add_data($insert);
        if (!$add_res) {
            $this->set_error(__FUNCTION__, "添加到需要推送的数据列表失败");
            return false;
        }

        // 添加推送数据
        WeChatPushJobs::ArticlePushJobs($add_res);
        return $add_res;
    }

    /**
     * 获取需要推送的数据列表
     * @return array
     * @throws \think\Exception
     */
    public function getPushList()
    {
        $map = array(
            'is_push' => -1,
            'push_time' => array(
                'elt', date('Y-m-d H:i:s')
            ),
            'is_delay' => 1
        );

        $list = $this->muti_get_data_by_where($map);
        return $list ? $this->fill_push_list($list) : array();
    }

    /**
     * 完善推送数据列表
     * @param $list
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function fill_push_list($list)
    {
        if (!$list) {
            return array();
        }
        $coinModel = CoinRuntimeModel::getInstance();
        $coin_id_list = array_column($list, 'coin_id');
        $coinDataList = $coinModel->muti_get_data_by_id_list($coin_id_list);
        foreach ($list as &$v) {
            $type = $v['type'];
            $id = $v['article_id'];
            $coin_id = $v['coin_id'];
            // 兼容
            $coinData = $coin_id ? $coinDataList[$coin_id] : false;
            $v['symbol'] = $coinData ? $coinData['symbol'] : false;

            switch ($type) {
                case self::TypeArticle :
                    // 文章类型
                    $articleModel = PublishArticleModel::getInstance();
                    $articleData = $articleModel->get_data_by_id($id);
                    $share_content = $articleData['summary'] ?: strip_tags($articleData['content']);
                    $share_content = str_replace(array(" ", "&nbsp;", chr(0xc2) . chr(0xa0)), '', $share_content);
                    $share_content = CommonFun::subtext($share_content, 100);
                    $v['title'] = $articleData['title'];
                    $v['url'] = $this->getPushUrl($articleData['h5_url']);
                    $v['remark'] = $share_content;
                    break;
                case self::TypeWeiBo :
                    // 微博类型
                    $weiboModel = PublishWeiboModel::getInstance();
                    $weiboData = $weiboModel->get_data_by_id($id);
                    $share_content = strip_tags($weiboData['content']);
                    $share_content = str_replace(array(" ", "&nbsp;", chr(0xc2) . chr(0xa0)), '', $share_content);
                    $share_content = CommonFun::subtext($share_content, 100);
                    $v['title'] = $weiboData['content'];
                    $v['url'] = $this->getPushUrl($weiboData['h5_url']);
                    $v['remark'] = $share_content;
                    break;
            }
        }
        return $list;
    }

    /**
     * @param $article
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fill_push($article)
    {

        if (!$article) {
            return array();
        }

        $coinModel = CoinRuntimeModel::getInstance();
        $coin_info = $coinModel->get_data_by_id($article['coin_id']);

        $type = $article['type'];
        $id = $article['article_id'];

        $article['symbol'] = $coin_info ? $coin_info['symbol'] : false;

        switch ($type) {
            case self::TypeArticle :
                // 文章类型
                $articleModel = PublishArticleModel::getInstance();
                $articleData = $articleModel->get_data_by_id($id);
                $share_content = $articleData['summary'] ?: strip_tags($articleData['content']);
                $share_content = str_replace(array(" ", "&nbsp;", chr(0xc2) . chr(0xa0)), '', $share_content);
                $share_content = CommonFun::subtext($share_content, 100);
                $article['title'] = $articleData['title'];
                $article['url'] = $this->getPushUrl($articleData['h5_url']);
                $article['remark'] = $share_content;
                break;
            case self::TypeWeiBo :
                // 微博类型
                $weiboModel = PublishWeiboModel::getInstance();
                $weiboData = $weiboModel->get_data_by_id($id);
                $share_content = strip_tags($weiboData['content']);
                $share_content = str_replace(array(" ", "&nbsp;", chr(0xc2) . chr(0xa0)), '', $share_content);
                $share_content = CommonFun::subtext($share_content, 100);
                $article['title'] = $weiboData['content'];
                $article['url'] = $this->getPushUrl($weiboData['h5_url']);
                $article['remark'] = $share_content;
                break;
        }
        return $article;
    }

    /**
     * @param string $type
     * @return array|bool
     * @throws \think\Exception
     */
    public function getArticleIds($type = 'article')
    {
        $map = array(
            'type' => $type,
        );
        $res = $this->search_id_list_no_page($map, 'article_id');
        if (!$res) {
            return false;
        }
        return array_unique($res);
    }

    /**
     * @param $url
     * @return mixed
     */
    private function getPushUrl($url)
    {
        return $url;
    }

    /**
     * 获取币种推送统计
     * @param int|array $coin_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDayPushCount($coin_id = 0)
    {
        $where = array(
            'push_time' => array(
                'between', array(
                    date('Y-m-d 00:00:00'),
                    date('Y-m-d H:i:s')
                ),
            ),
        );
        if ($coin_id) {
            $coin_id_set = is_array($coin_id) ? array_unique($coin_id) : [$coin_id];
            $where['coin_id'] = ['in', $coin_id_set];
        }

        $list = $this->field('count(*) as count,coin_id')->where($where)->group('coin_id')->select();
        $article_push_count_format = array();
        $list = $list ?: [];
        foreach ($list as $value) {
            $article_push_count_format[$value['coin_id']] = $value['count'];
        }
        return $article_push_count_format;
    }

    /**
     * 获取24h币种推送列表
     * @param $coin_id
     * @return array|bool|mixed
     * @throws \think\Exception
     */
    public function getDayPushList($coin_id)
    {
        if ($coin_id == 0) {
            $map['coin_id'] = 0;
        } else {
            $map['coin_id'] = ['in', $coin_id];
        }
        $map['push_time'] = array('between', [date('Y-m-d 00:00:00', strtotime('-1 day')), date('Y-m-d H:i:s')]);
        $aids = $this->where($map)->column("article_id");
        if ($aids) {
            rsort($aids);
            $modelAdmin = RbacAdminModel::getInstance();
            $articleModel = PublishArticleModel::getInstance();
            $lists = $articleModel->muti_get_data_by_id_list($aids, true, true, false);
            if (!empty($lists)) {
                foreach ($lists as &$v) {
                    if ($v['publish_user'] > 0) {
                        $username = $modelAdmin->where(['id' => $v['publish_user']])->value("real_name");
                        $v['publish_user'] = $username;
                    }
                }
            }
            return $lists;
        }
        return [];
    }

    /**
     * 获取48h币种推送列表
     * @param $exchange_id
     * @return array|bool|mixed
     * @throws \think\Exception
     */
    public function getExchangePushList($exchange_id)
    {
        if (!$exchange_id) {
            return false;
        }
        $map['coin_id'] = -2;
        $map['exchange_id'] = ['in', $exchange_id];
        $map['push_time'] = ['between', [date('Y-m-d 00:00:00', strtotime('-2 day')), date('Y-m-d H:i:s')]];
        $aids = $this->where($map)->column("article_id");
        if ($aids) {
            rsort($aids);
            $modelAdmin = RbacAdminModel::getInstance();
            $articleModel = PublishArticleModel::getInstance();
            $lists = $articleModel->muti_get_data_by_id_list($aids, true, true, false);
            if (!empty($lists)) {
                foreach ($lists as &$v) {
                    if ($v['publish_user'] > 0) {
                        $username = $modelAdmin->where(['id' => $v['publish_user']])->value("real_name");
                        $v['publish_user'] = $username;
                    }
                }
            }
            return $lists;
        }
        return [];
    }

    /**
     * 获取各类型的推送列表
     * @param $map
     * @return array|bool
     * @throws \think\Exception
     */
    public function getArticlePushList($map)
    {
        if (!$map) {
            return false;
        }
        $res = $this->search_id_list_no_page($map, 'article_id');
        if (!$res) {
            return false;
        }
        return array_unique($res);
    }

    /**
     * 获取发送记录
     * @param $article_id
     * @return bool|int|string
     * @throws \think\Exception
     */
    public function getWechatList($article_id)
    {
        if (!$article_id) {
            return false;
        }
        $count = $this->where(['article_id' => $article_id, 'is_push' => 1])->count();
        if ($count > 0) {
            return $count;
        }
        return false;
    }

    /**
     * 获取1小时服务号推送数量
     * @return bool|int|string
     * @throws \think\Exception
     */
    public function getWechatNoticeNum()
    {
        $map['is_push'] = 1;
        $map['push_time'] = array('between', [date('Y-m-d H:i:s', strtotime('-1 hour')), date('Y-m-d H:i:s')]);
        $count = $this->where($map)->count();
        if ($count > 0) {
            return $count;
        }
        return false;
    }
}